from flask import Flask, render_template_string
from flask_socketio import SocketIO, send

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Local Chat Room</title>
    <style>
        body { font-family: Arial, sans-serif; background-color: #e9ecef; margin: 0; padding: 0; }
        #chat { max-width: 600px; margin: 50px auto; padding: 20px; background-color: #ffffff; border-radius: 8px; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2); }
        h2 { text-align: center; color: #343a40; }
        #message-box { border: 1px solid #ccc; padding: 10px; height: 400px; overflow-y: auto; background-color: #f9f9f9; border-radius: 4px; margin-bottom: 10px; display: flex; flex-direction: column; align-items: flex-end; }
        #message-box p { margin: 5px 0; padding: 10px; border-radius: 10px; background-color: #007BFF; color: white; max-width: 80%; word-wrap: break-word; align-self: flex-end; }
        #input-box { display: flex; }
        #input-box input { flex: 1; padding: 10px; border: 1px solid #ccc; border-radius: 20px; margin-right: 10px; transition: border-color 0.3s; }
        #input-box input:focus { border-color: #007BFF; outline: none; }
        #input-box button { padding: 10px 15px; background-color: #007BFF; color: white; border: none; border-radius: 20px; cursor: pointer; transition: background-color 0.3s; }
        #input-box button:hover { background-color: #0056b3; }
    </style>
</head>
<body>
    <div id="chat">
        <h2>聊天室</h2>
        <div id="message-box"></div>
        <div id="input-box">
            <input type="text" id="message-input" placeholder="输入你的消息...">
            <button onclick="sendMessage()">发送</button>
        </div>
    </div>

    <script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>
    <script type="text/javascript">
        const socket = io();

        socket.on('message', function(msg) {
            const messageBox = document.getElementById('message-box');
            const newMessage = document.createElement('p');
            newMessage.textContent = msg;
            messageBox.appendChild(newMessage);
            messageBox.scrollTop = messageBox.scrollHeight; // 滚动到最新消息
        });

        function sendMessage() {
            const input = document.getElementById('message-input');
            const message = input.value.trim();
            if (message) {
                socket.send(message);
                input.value = ''; // 清空输入框
                input.focus(); // 重新聚焦输入框
            }
        }

        document.getElementById("message-input").addEventListener("keypress", function(event) {
            if (event.key === "Enter") {
                sendMessage();
            }
        });
    </script>
</body>
</html>
"""

@app.route('/')
def chat():
    return render_template_string(HTML_TEMPLATE)

@socketio.on('message')
def handle_message(msg):
    print('Received message:', msg)
    send(msg, broadcast=True)

if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', port=5000, debug=True)